import Vue from "vue";
import axios from "axios";
import { MessageBox } from "element-ui";

const $http = axios.create({
  baseURL: "/api",
});

export default ({ store, redirect }) => {
  // 请求拦截
  $http.interceptors.request.use((config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.common["Authorization"] = "Bearer " + token;
    }

    return config;
  });

  // 响应拦截
  $http.interceptors.response.use((response) => {
    const { data } = response;

    if (data.code === -666) {
      MessageBox.confirm(data.message, "过期", {
        confirmButtonText: "登录",
        showCancelButton: false,
        type: "warning",
      }).then(() => {
        localStorage.removeItem("token");
        redirect({ path: "login" });
      });
      // Vue.$router.push("/login");
    }

    return data;
  });
};

Vue.prototype.$http = $http;
 
